"""
Anomaly detection node - identifies anomalies in the target metric.
"""
from typing import Dict, Any
from ..tools.anomaly_detector import AnomalyDetector


def detect_anomalies(state: Dict[str, Any]) -> Dict[str, Any]:
    """
    Detect anomalies in the target metric.

    Args:
        state: Current state dict

    Returns:
        Updated state dict with anomalies detected
    """
    data = state.get('data')
    target_metric = state.get('target_metric', 'revenue')
    config = state.get('config', {})

    if data is None or data.empty:
        state['anomalies'] = []
        state['next_action'] = 'decompose_metric'
        return state

    # Initialize anomaly detector
    threshold = config.get('anomaly_threshold', 2.0)
    detector = AnomalyDetector(threshold=threshold)

    # Detect anomalies
    try:
        anomalies = detector.detect_anomalies(
            data,
            metric_column=target_metric,
            time_column='date',
            method='zscore'
        )

        state['anomalies'] = [a.dict() for a in anomalies]

        # Determine next action based on anomalies
        if anomalies:
            # If anomalies found, proceed to drill down
            state['next_action'] = 'drill_down'
            state['should_continue_drill'] = True
        else:
            # No anomalies, go straight to decomposition
            state['next_action'] = 'decompose_metric'
            state['should_continue_drill'] = False

    except Exception as e:
        state['error'] = f"Anomaly detection failed: {str(e)}"
        state['anomalies'] = []
        state['next_action'] = 'decompose_metric'

    return state
